#include "pwm.h"
#include "delay.h"

void TIM4_PWM_Init(void)
{
	TIM_TimeBaseInitTypeDef tim;
	TIM_OCInitTypeDef ocx;
	GPIO_InitTypeDef gpio;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

	GPIO_PinAFConfig(GPIOD, GPIO_PinSource12, GPIO_AF_TIM4);
	GPIO_PinAFConfig(GPIOD, GPIO_PinSource13, GPIO_AF_TIM4);

	gpio.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13;
	gpio.GPIO_Mode = GPIO_Mode_AF;
	gpio.GPIO_Speed = GPIO_Speed_100MHz;
	gpio.GPIO_OType = GPIO_OType_PP;
	gpio.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOD, &gpio);

	tim.TIM_Prescaler = 90 - 1; //90M internal clock
	tim.TIM_CounterMode = TIM_CounterMode_Up;
	tim.TIM_ClockDivision = TIM_CKD_DIV1;
	tim.TIM_Period = 20000 - 1;
	TIM_TimeBaseInit(TIM4, &tim);
	TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE);
	TIM_Cmd(TIM4, ENABLE);

	NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
//	ocx.TIM_OCMode = TIM_OCMode_PWM1;
//	ocx.TIM_OutputState = TIM_OutputState_Enable;
//	ocx.TIM_Pulse = 0;
//	ocx.TIM_OCPolarity = TIM_OCPolarity_High;

//	TIM_OC1Init(TIM4, &ocx);
//	TIM_OC2Init(TIM4, &ocx);
//	TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable);
//	TIM_OC2PreloadConfig(TIM4, TIM_OCPreload_Enable);

	TIM_ARRPreloadConfig(TIM4, ENABLE);
	TIM_Cmd(TIM4, ENABLE);

	//		TIM4->CCR1=1000;
	//		TIM4->CCR2=1000;
	//		delay_ms(2000);
}

int time_20ms = 0;
int time_1s = 0;
void TIM4_IRQHandler()
{
	if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET)
	{

		time_20ms++;
		if (time_20ms > 50)
		{
			time_20ms = 0;
			time_1s++;
		}
		TIM_ClearFlag(TIM4, TIM_IT_Update);
	}
}
void Heat_PWM_Init(void)
{
	TIM_TimeBaseInitTypeDef tim;
	TIM_OCInitTypeDef ocx;
	GPIO_InitTypeDef gpio;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

	GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_TIM3);

	gpio.GPIO_Pin = GPIO_Pin_5;
	gpio.GPIO_Mode = GPIO_Mode_AF;
	gpio.GPIO_Speed = GPIO_Speed_100MHz;
	gpio.GPIO_OType = GPIO_OType_PP;
	gpio.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_Init(GPIOB, &gpio);

	tim.TIM_Prescaler = 900 - 1; //90M internal clock
	tim.TIM_CounterMode = TIM_CounterMode_Up;
	tim.TIM_ClockDivision = TIM_CKD_DIV1;
	tim.TIM_Period = 2000;
	TIM_TimeBaseInit(TIM3, &tim);
	TIM_Cmd(TIM3, ENABLE);

	ocx.TIM_OCMode = TIM_OCMode_PWM1;
	ocx.TIM_OutputState = TIM_OutputState_Enable;
	ocx.TIM_OutputNState = TIM_OutputNState_Disable;
	ocx.TIM_Pulse = 0;
	ocx.TIM_OCPolarity = TIM_OCPolarity_High;
	ocx.TIM_OCNPolarity = TIM_OCPolarity_High;
	ocx.TIM_OCIdleState = TIM_OCIdleState_Reset;
	ocx.TIM_OCNIdleState = TIM_OCIdleState_Set;

	TIM_OC2Init(TIM3, &ocx);
	TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);

	TIM_ARRPreloadConfig(TIM3, ENABLE);
	TIM_Cmd(TIM3, ENABLE);

	TIM3->CCR2 = 0;
}
